package cn.icanci.ladybird.controller;

import cn.icanci.ladybird.common.result.JsonData;
import cn.icanci.ladybird.common.util.cache.RedisUtils;
import cn.icanci.ladybird.pojo.dto.UserFlashSaleDTO;
import cn.icanci.ladybird.pojo.dto.UserProduceDTO;
import cn.icanci.ladybird.service.user.UserFlashSaleService;
import cn.icanci.ladybird.service.user.UserProduceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author: zxp
 * @date: Created in 2020/10/3 0003 下午 15:33
 * @classAction: 秒杀页面数据显示
 */
@SuppressWarnings("all")
@Controller
@RequestMapping("/api/v1/pub/user")
public class UserFlashSaleController {
    @Autowired
    private UserFlashSaleService userFlashSaleService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private UserProduceService userProduceService;

    @RequestMapping("/flash-sale")
    public String getUserIndexJson(Model model) {
        // 查询列表
        List<UserFlashSaleDTO> userFlashSaleDTOS = userFlashSaleService.userFlashSaleDTO();
        ArrayList<Object> list = new ArrayList<>();
        list.add(userFlashSaleDTOS);
        JsonData jsonData = JsonData.builderSuccess(list);
        model.addAttribute("jsonData", jsonData);
        return "user/flash-sale";
    }

    /**
     * 查询票的所有信息
     * @param model 视图
     * @param ticketId 票的id
     * @return 返回界面
     */
    @RequestMapping("/kill-sale")
    public String getKillSale(Model model, Long ticketId) {
        String key = "TicketData-" + ticketId;
        JsonData targetData = (JsonData) redisUtils.get(key);
        if (null == targetData) {
            UserProduceDTO userProduceDTO = userProduceService.queryUserProduceDTO(ticketId);
            JsonData jsonData = JsonData.builderSuccess(userProduceDTO);
            model.addAttribute("jsonData", jsonData);
            redisUtils.set(key, jsonData, 30, TimeUnit.MINUTES);
        } else {
            model.addAttribute("jsonData", targetData);
        }
        return "user/kill-details";
    }
}
